package security.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.filter.DelegatingFilterProxy;

@Controller
public class FilterShowController {
	/**
	 * when spring boot parent is 1.3.5, filterChainProxy is initiated by Spring
	 * but when parent is 1.5.9, you can't find this bean initiated by Spring
	 */
    @Autowired(required=false)
    private FilterChainProxy filterChainProxy;

    //private  DelegatingFilterProxy delegatingFilterProxy;
    
    private static Log LOG = LogFactory.getLog(FilterShowController.class);
    
    @RequestMapping("/filterChain")
    public @ResponseBody Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        return this.securityFilterChainProxy();
    }

    public Map<Integer, Map<Integer, String>> securityFilterChainProxy(){
    	UsernamePasswordAuthenticationFilter ufilter;
        Map<Integer, Map<Integer, String>> filterChains= new HashMap<Integer, Map<Integer, String>>();
        int i = 1;
        for(SecurityFilterChain secfc :  this.filterChainProxy.getFilterChains()){
            //filters.put(i++, secfc.getClass().getName());
            Map<Integer, String> filters = new HashMap<Integer, String>();
            int j = 1;
            for(Filter filter : secfc.getFilters()){
                filters.put(j++, filter.getClass().getName());
                LOG.info(j-1 + ": " + filter.getClass().getName());
            }
            filterChains.put(i++, filters);
        }
        return filterChains;
    }
}
